// Decompiled by Jad v1.5.7f. Copyright 2000 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/SiliconValley/Bridge/8617/jad.html
// Decompiler options: packimports(3) 
// Source File Name:   GroupServiceImp.java

package com.iphaeton.lms.business.organize;

import com.iphaeton.common.helper.Pagination;
import com.iphaeton.common.helper.UserSession;
import com.iphaeton.exception.BusinessException;
import com.iphaeton.exception.PersistenceException;
import com.iphaeton.lms.business.PersistentServiceSupport;
import com.iphaeton.lms.pojo.organize.*;
import com.iphaeton.persistence.IPersistenceService;
import com.iphaeton.persistence.spring.JdbcPService;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import org.apache.log4j.Logger;
import org.apache.struts.action.*;
import org.dom4j.*;

// Referenced classes of package com.iphaeton.lms.business.organize:
//            IGroupService, IOrganizeService

public class GroupServiceImp extends PersistentServiceSupport
    implements IGroupService
{

    public GroupServiceImp()
    {
        organize = null;
    }

    public IOrganizeService getOrganize()
    {
        return organize;
    }

    public void setOrganize(IOrganizeService organize)
    {
        this.organize = organize;
    }

    public Group updateGroup(Group g)
        throws BusinessException
    {
        if(g == null)
            throw new BusinessException("null g isn't allowed in function save(Group g)!");
        Group group = null;
        try
        {
            group = (Group)hbpservice.store(g);
        }
        catch(PersistenceException e)
        {
            e.printStackTrace();
            throw new BusinessException("can't save group '" + group.getName() + "'!");
        }
        return group;
    }

    public void remove(String id)
        throws BusinessException
    {
        if(id == null)
            throw new BusinessException("null id isn't allowed in function remove(String id)!");
        try
        {
            hbpservice.remove(id, com.iphaeton.lms.pojo.organize.Group.class);
        }
        catch(PersistenceException e)
        {
            e.printStackTrace();
            throw new BusinessException("can't remove group where id='" + id + "'!");
        }
    }

    public void remove(Group g)
        throws BusinessException
    {
        if(g == null)
            throw new BusinessException("null g isn't allowed in function remove(String id)!");
        try
        {
            hbpservice.remove(g);
        }
        catch(PersistenceException e)
        {
            e.printStackTrace();
            throw new BusinessException("can't remove group !");
        }
    }

    public Group findGroupById(String id)
        throws BusinessException
    {
        if(id == null)
            throw new BusinessException("null id isn't allowed in function findGroupById(String id)!");
        Group group = null;
        try
        {
            group = (Group)hbpservice.get(id, com.iphaeton.lms.pojo.organize.Group.class);
        }
        catch(PersistenceException e)
        {
            e.printStackTrace();
            throw new BusinessException("can't find group where id='" + id + "'!");
        }
        return group;
    }

    public Group addUser(Group g, User u)
        throws BusinessException
    {
        if(g == null || u == null)
            throw new BusinessException("null value isn't allowed in function addUser(Group g,User u)!");
        Set user = g.getUser();
        if(user == null)
            user = new HashSet();
        user.add(u);
        g.setUser(user);
        try
        {
            g = (Group)hbpservice.store(g);
        }
        catch(PersistenceException e)
        {
            e.printStackTrace();
            throw new BusinessException("\u7ED9\u7528\u6237\u7EC4\u6DFB\u52A0\u7528\u6237\u5931\u8D25!");
        }
        return g;
    }

    public void setManageGroup(Group g, User u)
        throws BusinessException
    {
        String sql = "select * from t_group g inner join t_user_group ug on g.id=ug.group_id and ug.id='" + u.getId() + "' and g.type='m'";
        try
        {
            List list = jdbcpservice.query(sql);
            if(list != null && list.size() > 0)
                sql = "update t_user_group set group_id='" + g.getId() + "' where id='" + u.getId() + "'";
            else
                sql = "insert into t_user_group (id,group_id) values ('" + u.getId() + "','" + g.getId() + "')";
            jdbcpservice.execute(sql);
        }
        catch(PersistenceException e)
        {
            e.printStackTrace();
        }
    }

    public void removeUser(Group g, String id)
        throws BusinessException
    {
        if(g == null || id == null)
            throw new BusinessException("null value isn't allowed in function removeUser(Group g, String id)!");
        Set user = g.getUser();
        Set newUser = new HashSet();
        User u = null;
        for(Iterator it = user.iterator(); it.hasNext();)
        {
            u = (User)it.next();
            if(!u.getId().equals(id))
                newUser.add(u);
        }

        g.setUser(newUser);
        try
        {
            hbpservice.store(g);
        }
        catch(PersistenceException e)
        {
            e.printStackTrace();
            throw new BusinessException("\u4ECE\u7528\u6237\u7EC4\u4E2D\u5220\u9664\u7528\u6237\u5931\u8D25!");
        }
    }

    public List findUser(String orgId, String groupId)
        throws BusinessException
    {
        if(groupId == null)
            throw new BusinessException("null groupId isn't allowed in function findUser(String orgId,Group g)!");
        List userList = new LinkedList();
        Set userSet = findGroupById(groupId).getUser();
        for(Iterator it = userSet.iterator(); it.hasNext();)
        {
            User temp = (User)it.next();
            if(orgId == null || "".equals(orgId) || organize.isChild(temp.getOrganize(), organize.findOrganizeById(orgId)))
                userList.add(temp);
        }

        return userList;
    }

    public Pagination findUserPagination(String queryType, int pageSize)
        throws BusinessException
    {
        if(queryType == null)
            logger.debug("^_^,it's just a passed into parameter for illustrating!");
        String selectHql = "select count(u.id) as count from t_user u inner join t_user_group ug on u.id=ug.id and ug.group_id='" + queryType + "'";
        List list = null;
        try
        {
            list = jdbcpservice.query(selectHql);
        }
        catch(PersistenceException e)
        {
            e.printStackTrace();
            throw new BusinessException("can't find user from group by " + queryType + "!");
        }
        int itemCount = list.size() <= 0 ? 0 : ((Integer)((Map)list.get(0)).get("count")).intValue();
        int totalPage = ((itemCount + pageSize) - 1) / pageSize;
        Pagination pageInfo = new Pagination(totalPage, itemCount, pageSize);
        return pageInfo;
    }

    public List findNotGroupUser(String queryType, String groupId, String organizeId)
        throws BusinessException
    {
        String sql = "select u.id as uid, u.state as state,u.user_id as userId,u.name as uname,o.id as oid,o.name as oname,o.url as ourl from t_user u inner join t_organize o on u.organize_id=o.id ";
        if(organizeId == null)
            sql = sql + " and o.url like '" + queryType + "%' ";
        else
            sql = sql + " and u.organize_id='" + organizeId + "' ";
        sql = sql + " and u.id not in (select id from t_user_group ug where ug.group_id='" + groupId + "')";
        List list = null;
        try
        {
            list = jdbcpservice.query(sql);
        }
        catch(PersistenceException e)
        {
            e.printStackTrace();
            throw new BusinessException("");
        }
        return list;
    }

    public List getGroupList(String type, String orgId)
        throws BusinessException
    {
        List list = null;
        String hql = "from Group g where g.type='" + type + "'";
        if(orgId != null && !"".equals(orgId))
            hql = hql + " and g.organizeId='" + orgId + "'";
        try
        {
            list = hbpservice.query(hql);
        }
        catch(PersistenceException e)
        {
            e.printStackTrace();
            throw new BusinessException("\u67E5\u8BE2\u7528\u6237\u7EC4\u5217\u8868\u51FA\u9519!");
        }
        return list;
    }

    public Document getUserDocument(String type, Train t)
        throws BusinessException
    {
        List group = null;
        Document doc = DocumentHelper.createDocument();
        Element root = doc.addElement("root");
        try
        {
            group = getGroupList(type, "");
        }
        catch(BusinessException e)
        {
            e.printStackTrace();
        }
        for(Iterator it = group.iterator(); it.hasNext();)
        {
            Group g = (Group)it.next();
            Element groupElement = root.addElement(g.getName());
            for(Iterator uIt = g.getUser().iterator(); uIt.hasNext();)
            {
                User u = (User)uIt.next();
                logger.debug(u.getOrganize().getUrl());
                logger.debug(t.getOrganize().getUrl());
                if(organize.isChild(u.getOrganize(), t.getOrganize()))
                {
                    Element user = groupElement.addElement("user");
                    user.setText(u.getName() + "[" + u.getUserId() + "]");
                    user.addAttribute("id", u.getId());
                }
            }

        }

        return doc;
    }

    public String findManagerGroup(String id)
        throws BusinessException
    {
        String sql = "select id from t_group where organize_id='" + id + "' and type='m'";
        List list = null;
        try
        {
            list = jdbcpservice.query(sql);
        }
        catch(PersistenceException e)
        {
            e.printStackTrace();
            throw new BusinessException("\u67E5\u8BE2\u7ED9\u5B9A\u7EC4\u7EC7\u7684\u7BA1\u7406\u7EC4\u5931\u8D25!");
        }
        String groupId = (String)((Map)list.get(0)).get("id");
        return groupId;
    }

    public List findGroupTrain(String group_id, String join)
        throws BusinessException
    {
        Calendar cal = Calendar.getInstance();
        java.util.Date time = cal.getTime();
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String currentTime = df.format(time);
        List list = null;
        String sql = "select t.id as tid from t_train t inner join t_group_train gt on gt.train_id=t.id and t.join_access='" + join + "'" + " inner join t_group g on g.id='" + group_id + "' and t.start_date<='" + currentTime + "' and t.end_date>='" + currentTime + "'";
        try
        {
            list = jdbcpservice.query(sql);
        }
        catch(PersistenceException e)
        {
            e.printStackTrace();
            throw new BusinessException("\u67E5\u8BE2\u7528\u6237\u7EC4\u57F9\u8BAD\u73ED\u5931\u8D25!");
        }
        return list;
    }

    public Document getGroupTree(String webRoot, String id, String type)
        throws BusinessException
    {
        Document doc = DocumentHelper.createDocument();
        Element root = doc.addElement("tree");
        List list = null;
        Organize org = getOrganize().findOrganizeById(id);
        if(!getOrganize().isLeaf(org))
        {
            Element child = root.addElement("tree");
            child.addAttribute("text", org.getName());
            if(type.equals("post"))
            {
                child.addAttribute("src", webRoot + "/organizeTxAction.do?method=getTree&type=op&id=" + id);
                child.addAttribute("action", webRoot + "/organizeTxAction.do?method=userMovePrepare&id=" + id + "&type=op");
            } else
            if(type.equals("duty"))
            {
                child.addAttribute("src", webRoot + "/organizeTxAction.do?method=getTree&type=od&id=" + id);
                child.addAttribute("action", webRoot + "/organizeTxAction.do?method=userMovePrepare&id=" + id + "&type=od");
            }
            list = getOrganize().findGroup(getOrganize().findRoot(), 'z');
            child.addAttribute("target", "operateFrame");
            child.addAttribute("expended", "false");
        }
        if(type.equals("post"))
            list = getOrganize().findGroup(getOrganize().findRoot(), 'g');
        else
        if(type.equals("duty"))
            list = getOrganize().findGroup(getOrganize().findRoot(), 'z');
        for(int i = 0; list != null && i < list.size(); i++)
        {
            Group temp = (Group)list.get(i);
            Element element = root.addElement("tree");
            element.addAttribute("text", temp.getName());
            element.addAttribute("action", webRoot + "/organizeTxAction.do?method=userMovePrepare&id=" + temp.getId() + "&type=" + type);
            if(type.equals("post"))
                element.addAttribute("icon", webRoot + "/images/xtree/post.gif");
            else
            if(type.equals("duty"))
                element.addAttribute("icon", webRoot + "/images/xtree/duty.gif");
            element.addAttribute("target", "operateFrame");
            element.addAttribute("expended", "false");
        }

        return doc;
    }

    public Pagination selectUser(String id, String row, int pageSize)
        throws BusinessException
    {
        String selectHql = "select count(u) from User u where u.group.id='" + id + "'";
        String hqlQueryStr = "from User u where u.group.id='" + id + "'";
        if(row != null && !"".equals(row))
            hqlQueryStr = hqlQueryStr + " order by u." + row;
        else
            hqlQueryStr = hqlQueryStr + " order by u.userId";
        List list = null;
        try
        {
            list = hbpservice.query(selectHql);
        }
        catch(PersistenceException e)
        {
            e.printStackTrace();
            throw new BusinessException("can't find train!");
        }
        int itemCount = list.size() <= 0 ? 0 : ((Integer)list.get(0)).intValue();
        int totalPage = ((itemCount + pageSize) - 1) / pageSize;
        Pagination pageInfo = new Pagination(totalPage, itemCount, pageSize);
        pageInfo.setHqlQueryString(hqlQueryStr);
        return pageInfo;
    }

    public ActionForward exportTemplate(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException
    {
        String name = request.getRealPath("/") + "template/group.xls";
        UserSession userSession = (UserSession)request.getSession().getAttribute("userSession");
        String manageId = userSession.getManageOrgId();
        List list;
        try
        {
            list = organize.findAllChildOrganize(organize.findOrganizeById(manageId));
        }
        catch(BusinessException e)
        {
            e.printStackTrace();
            request.setAttribute("exception", e);
            return mapping.findForward("failure");
        }
        request.setAttribute("list", list);
        request.setAttribute("name", name);
        return mapping.findForward("group_template");
    }

    public List findPageList(Pagination pageInfo)
    {
        List list = null;
        try
        {
            list = getSpecifiedItems(pageInfo);
        }
        catch(BusinessException e)
        {
            e.printStackTrace();
        }
        return list;
    }

    private static Logger logger;
    protected IOrganizeService organize;
    static Class class$0; /* synthetic field */
    static Class class$1; /* synthetic field */

    static 
    {
        logger = Logger.getLogger(com.iphaeton.lms.business.organize.GroupServiceImp.class.getName());
    }
}
